import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/handle/xindong_common_handle.dart';
import 'package:xindong/manager/xindong_record_voice_ctr.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/routes/user/auth/xindong_auth_ctr.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:svgaplayer_flutter/player.dart';

class XinDongAuthVoiceYeMian extends StatefulWidget {
  const XinDongAuthVoiceYeMian({super.key});

  @override
  State<XinDongAuthVoiceYeMian> createState() => _XinDongAuthVoiceYeMianState();
}

class _XinDongAuthVoiceYeMianState extends State<XinDongAuthVoiceYeMian> {
  static const kTagAuthVoice = "AuthVoice";
  final _controller = Get.put(XinDongRecordVoiceCtr(), tag: kTagAuthVoice);
  final _commonHandle = XinDongCommonHandle();

  String authSlogan = "";
  int channel = 1;
  String voicePath = "";
  int voiceTime = 0;

  void refreshSlogan() async {
    final result = await _commonHandle.requestAuthSlogan();
    if (result != null) {
      setState(() {
        authSlogan = result["content"];
        channel = result["channel"];
      });
    }
  }

  void onStart() {
    _controller.startRecord(onRecordResult: (bool result, double seconds, String path) {
      if (result) {
        voicePath = path;
        voiceTime = seconds.ceil();
      } else {
        voicePath = "";
        voiceTime = 0;
      }
    });
  }

  void onSubmit() {
    XinDongAuthCtr.to.requestAuthVoice(filePath: voicePath, duration: voiceTime);
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      refreshSlogan();
    });
  }


  @override
  void dispose() {
    _controller.resetRecord();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XinDongAppBar("语音签名"),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              height: 200,
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              margin: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(color: DZColors.cellColor, borderRadius: BorderRadius.circular(16)),
              child: Column(
                children: [
                  Text(
                    channel == 1 ? "读一段话" : "唱一段歌词",
                    style: const TextStyle(fontSize: 15, color: DZColors.titleColor),
                  ),
                  Expanded(
                    child: Container(
                      alignment: Alignment.topLeft,
                      padding: const EdgeInsets.only(top: 16),
                      child: Text(
                        authSlogan,
                        style: const TextStyle(fontSize: 15, color: DZColors.contentColor),
                      ),
                    ),
                  ),
                  TextButton(
                    onPressed: () => refreshSlogan(),
                    child: const Text.rich(
                      TextSpan(children: [
                        WidgetSpan(
                          child: Icon(Icons.refresh, size: 18, color: DZColors.titleColor),
                        ),
                        TextSpan(text: " 换一个")
                      ]),
                      style: TextStyle(fontSize: 15, color: DZColors.titleColor),
                    ),
                  ),
                ],
              ),
            ),
            GetBuilder<XinDongRecordVoiceCtr>(
                tag: kTagAuthVoice,
                builder: (controller) {
                  return Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          height: 20,
                          margin: const EdgeInsets.only(bottom: 32),
                          child: _buildStateWidget(controller),
                        ),
                        SizedBox(
                          height: 62,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              controller.recordCompleted
                                  ? _buildActionButton(
                                name: "重录",
                                iconName: AssetsRes.ICON_VOICE_RELOAD,
                                onTap: () => controller.resetRecord(),
                              )
                                  : const SizedBox(),
                              _buildRecordButton(controller),
                              controller.recordCompleted
                                  ? _buildActionButton(
                                name: "提交",
                                iconName: AssetsRes.ICON_VOICE_DONE,
                                onTap: onSubmit,
                              )
                                  : const SizedBox(),
                            ],
                          ),
                        ),
                        Container(
                          height: 60,
                          alignment: Alignment.bottomCenter,
                          child: Text(
                            channel == 1 ? "点击开始朗读或者自由发挥" : "点击开始演唱或者自由发挥",
                            style: const TextStyle(fontSize: 14, color: DZColors.contentColor),
                          ),
                        ),
                      ],
                    ),
                  );
                }
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStateWidget(XinDongRecordVoiceCtr recordVoiceController) {
    if (recordVoiceController.voiceState == XinDongRecordVoiceState.none ||
        recordVoiceController.voiceState == XinDongRecordVoiceState.allowRecording) {
      return const SizedBox();
    }
    if (recordVoiceController.voiceState == XinDongRecordVoiceState.completed ||
        recordVoiceController.voiceState == XinDongRecordVoiceState.playingPause) {
      return Text(recordVoiceController.timeText);
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const SizedBox(width: 80, height: 17, child: SVGASimpleImage(assetsName: AssetsRes.VOICE)),
        const SizedBox(width: 10),
        Text(recordVoiceController.timeText),
        const SizedBox(width: 10),
        const SizedBox(width: 80, height: 17, child: SVGASimpleImage(assetsName: AssetsRes.VOICE)),
      ],
    );
  }

  Widget _buildActionButton({required String name, required String iconName, required Function() onTap}) {
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque,
      child: Column(
        children: [
          ImageUtil.asset(iconName, width: 35, height: 35),
          const SizedBox(height: 5),
          Text(name, style: const TextStyle(color: DZColors.contentColor, fontSize: 12)),
        ],
      ),
    );
  }

  Widget _buildRecordButton(XinDongRecordVoiceCtr recordVoiceController) {
    String iconName = AssetsRes.ICON_VOICE_START;
    switch (recordVoiceController.voiceState) {
      case XinDongRecordVoiceState.none:
      case XinDongRecordVoiceState.allowRecording:
        iconName = AssetsRes.ICON_VOICE_START;
        break;
      case XinDongRecordVoiceState.recording:
        iconName = AssetsRes.ICON_VOICE_STOP;
        break;
      case XinDongRecordVoiceState.playing:
        iconName = AssetsRes.ICON_VOICE_PAUSE;
        break;
      case XinDongRecordVoiceState.playingPause:
      case XinDongRecordVoiceState.completed:
        iconName = AssetsRes.ICON_VOICE_PLAY;
        break;
      default:
        break;
    }
    return GestureDetector(
      onTap: () async {
        switch (recordVoiceController.voiceState) {
          case XinDongRecordVoiceState.none:
          case XinDongRecordVoiceState.allowRecording:
            final result = await recordVoiceController.checkPermission();
            if (result) {
              onStart();
            }
            break;
          case XinDongRecordVoiceState.recording:
            recordVoiceController.stopRecord();
            break;
          case XinDongRecordVoiceState.playing:
          case XinDongRecordVoiceState.playingPause:
            recordVoiceController.pausePlayVoice();
            break;
          case XinDongRecordVoiceState.completed:
            recordVoiceController.playVoice();
            break;
          default:
            break;
        }
      },
      behavior: HitTestBehavior.opaque,
      child: ImageUtil.asset(iconName, width: 52, height: 52, fit: BoxFit.cover),
    );
    // return GestureDetector(
    //   onTapDown: (detail) => recordVoiceController.checkPermission(),
    //   onLongPressStart: (detail) => recordVoiceController.startRecord(),
    //   onLongPressEnd: (detail) => recordVoiceController.stopRecord(),
    //   onLongPressMoveUpdate: _onLongPressUpdate,
    //   onLongPressCancel: _onLonePressCancel,
    //   child: Container(
    //     child: ImageHelper.asset(iconName, width: 52, height: 52, fit: BoxFit.cover),
    //   ),
    // );
  }
}
